//`timescale 1ns / 1ps

module fcram
(	
	// CPU
	input osc50,
	input m2,
	input m2_rst,
	input romsel,
	input cpu_rw_in,
	output irq,
	
	input [7:0]  cpu_data,
	input [14:0] cpu_addr_in,
	// 输出高位地址线
	output reg [21:13] prg_addr_out,
	
	input prg_addr_out_A_1,
	output byte1,
	
	// 片选
	output prg_ce,
	output prg_we,
	output prg_oe,
	
	
	// PPU
	input ppu_rd,
	input ppu_wr,
	input ppu_ce,
	input [12:10] ppu_addr_in,
	
	output chr_ce,
	output chr_oe,
	output chr_we,
	output chr_ce2,
	
	// 镜像
	output ppu_ciram_a10,
	
	// H
	input  ppu_A13_ne,
	output  ciram_ce,
	
	output reg [17:10] chr_addr_out
	
);

	assign byte1 = 1;
	
	// 只使用芯片1 接OE使用时候与WR取反 CE使用romsel
	assign prg_ce = romsel;
	assign prg_we = cpu_rw_in | romsel;
	assign prg_oe = ~cpu_rw_in | romsel;
	
	assign chr_ce = ppu_ce;
	assign chr_we = ppu_wr;
	assign chr_oe = ppu_rd;
	assign chr_ce2 = 1;
	
	//assign ciram_ce = ppu_A13_ne;
	assign ciram_ce = ~ppu_ce;
	
	assign irq = 1'bZ;
	
	initial
	begin
		prg_addr_out[21:14] <= 8'hff;
		chr_addr_out[17:10] <= 0;
	end
	
	// 0-V 
	// 1-H
	reg mirror = 1;
	assign ppu_ciram_a10 = mirror? ppu_addr_in[11] : ppu_addr_in[10];
	
	
	//===========
	
	
	// mapper226 prg-2M
	//Range, Mask:  $8000-FFFF, $8001
	//$8000:  [PMOP PPPP]
	//  P = Low 6 bits of PRG Reg
	//  M = Mirroring (0=Horz, 1=Vert)
	//  O = PRG Mode
	//$8001:  [.... ...H]
	//  H = high bit of PRG
	
	// 关闭bank切换
	reg bank_en = 1;
	reg prg_mode = 0;
	reg high_bit = 0;
	reg [5:0] prg_bank = 6'b000000;
	
	assign prg_addr_out[13] = cpu_addr_in[13];
	assign prg_addr_out[20] = high_bit;
	assign prg_addr_out[19:14] = prg_mode ? prg_bank : {prg_bank[5:1], cpu_addr_in[14]};
	assign chr_addr_out[12:10] = ppu_addr_in[12:10];
	
	always @ (negedge m2)
	begin
		if (!m2_rst)
		begin
			if(bank_en)
			begin
				prg_bank <= 6'b000000;
				high_bit <= 1'b0;
				prg_mode <= 1'b0;
			end
		end
		
		else if (cpu_rw_in == 0 && {!romsel,cpu_addr_in[14:0]} == 16'h8000 && bank_en)
		begin
			prg_bank <= {cpu_data[7], cpu_data[4:0]};
			mirror <= ~cpu_data[6];
			prg_mode <= cpu_data[5];
		end
			

		else if (cpu_rw_in == 0 && {!romsel,cpu_addr_in[14:0]} == 16'h5000)
		begin
			bank_en <= cpu_data[0];
			prg_mode <= cpu_data[1];
		end

		//prg
		else if (cpu_rw_in == 0 && {!romsel,cpu_addr_in[14:0]} == 16'h5001)
		begin
			prg_bank <= cpu_data[5:0];
		end
	end
	
	
	
endmodule

	
	

   